require("../css/commCss/normalize.less");
require("../css/commCss/reset.less");
require("../css/commCss/property.less");
require("../css/commCss/basic.less");
require("../css/register.less");

//验证码插件
const CaptchaMini = require("captcha-mini");

//axios
const axios = require("axios");

document.addEventListener("DOMContentLoaded", function () {
  /* 获取元素 */
  const phone = document.querySelector("#phone"); //手机号
  const captchas = document.querySelector("#captchas"); //验证码
  const firstPwd = document.querySelector("#firstPwd"); //密码
  const lastPwd = document.querySelector("#lastPwd"); //再次确认密码
  const regBtn = document.querySelector("#regBtn"); //注册账号
  const errMsg = document.querySelector("#errMsg"); //错误验证

  /* 定义数据 */
  let captchaCode = "";

  /* 
  1.验证码
   */

  /*传值,参数配置值，选择性配置*/
  let captcha = new CaptchaMini({
    lineWidth: 1, //线条宽度
    lineNum: 0, //线条数量
    dotR: 2, //点的半径
    dotNum: 0, //点的数量
    preGroundColor: [0, 40], //前景色区间
    backGroundColor: [220, 255], //背景色区间
    fontSize: 48, //字体大小
    fontFamily: ["Georgia", "微软雅黑", "Helvetica", "Arial"], //字体类型
    fontStyle: "fill", //字体绘制方法，有fill和stroke
    content: "abcdefghijklmnopqrstuvw1234567890", //验证码内容
    length: 4, //验证码长度
  });
  captcha.draw(document.querySelector("#captcha"), function (r) {
    // r : 验证码
    console.log(r);
    captchaCode = r;
  });

  /* 
  2.点击注册按钮，触发注册验证 
  */
  regBtn.addEventListener("click", function () {
    const phoneVal = phone.value; //手机号
    const captchasVal = captchas.value; //验证码
    const firstPwdVal = firstPwd.value; //密码
    const lastPwdVal = lastPwd.value; //再次确认密码

    if (!/^1[3-9][0-9]{9}$/.test(phoneVal)) {
      errMsg.textContent = "手机号错误";
      return;
    } else if (captchasVal != captchaCode) {
      errMsg.textContent = "验证码错误";
      return;
    } else if (!/^[a-zA-Z]\w{5,11}$/.test(firstPwdVal)) {
      //以字母开头，后面跟字母，数字，下划线
      errMsg.textContent = "密码错误";
      return;
    } else if (lastPwdVal != firstPwdVal) {
      errMsg.textContent = "密码不一致";
      return;
    } else {
      //清空错误信息
      errMsg.textContent = "";

      axios
        .post("http://139.9.177.51:8099/users/add", {
          account: phone.value,
          password: firstPwd.value,
        })
        .then(function (res) {
          if (res.data.status === 0) {
            location.href = "./login.html";
            console.log("成功");
          } else {
            console.log("失败");
          }
        });
    }
  });
});
